3 use Wikimedia\Rdbms\Blob
;
4 use Wikimedia\Rdbms\Database
;
5 use Wikimedia\Rdbms\DatabaseSqlite
;
7 class DatabaseSqliteMock
extends DatabaseSqlite
{
10 public static function newInstance( array $p = [] ) {
11 $p['dbFilePath'] = ':memory:';
14 return Database
::factory( 'SqliteMock', $p );
17 function query( $sql, $fname = '', $tempIgnore = false ) {
18 $this->lastQuery
= $sql;
24 * Override parent visibility to public
26 public function replaceVars( $s ) {
27 return parent
::replaceVars( $s );
36 class DatabaseSqliteTest
extends MediaWikiTestCase
{
37 /** @var DatabaseSqliteMock */
40 protected function setUp() {
43 if ( !Sqlite
::isPresent() ) {
44 $this->markTestSkipped( 'No SQLite support detected' );
46 $this->db
= DatabaseSqliteMock
::newInstance();
47 if ( version_compare( $this->db
->getServerVersion(), '3.6.0', '<' ) ) {
48 $this->markTestSkipped( "SQLite at least 3.6 required, {$this->db->getServerVersion()} found" );
52 private function replaceVars( $sql ) {
53 // normalize spacing to hide implementation details
54 return preg_replace( '/\s+/', ' ', $this->db
->replaceVars( $sql ) );
57 private function assertResultIs( $expected, $res ) {
58 $this->assertNotNull( $res );
60 foreach ( $res as $row ) {
61 foreach ( $expected[$i] as $key => $value ) {
62 $this->assertTrue( isset( $row->$key ) );
63 $this->assertEquals( $value, $row->$key );
67 $this->assertEquals( count( $expected ), $i, 'Unexpected number of rows' );
70 public static function provideAddQuotes() {
76 'foo bar', "'foo bar'"
78 [ // #2: including quote
79 'foo\'bar', "'foo''bar'"
81 // #3: including \0 (must be represented as hex, per https://bugs.php.net/bug.php?id=63419)
86 [ // #4: blob object (must be represented as hex)
98 * @dataProvider provideAddQuotes()
99 * @covers DatabaseSqlite::addQuotes
101 public function testAddQuotes( $value, $expected ) {
103 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
104 $this->assertEquals( $expected, $db->addQuotes( $value ), 'string not quoted as expected' );
106 // ok, quoting works as expected, now try a round trip.
107 $re = $db->query( 'select ' . $db->addQuotes( $value ) );
109 $this->assertTrue( $re !== false, 'query failed' );
111 $row = $re->fetchRow();
113 if ( $value instanceof Blob
) {
114 $value = $value->fetch();
117 $this->assertEquals( $value, $row[0], 'string mangled by the database' );
119 $this->fail( 'query returned no result' );
124 * @covers DatabaseSqlite::replaceVars
126 public function testReplaceVars() {
127 $this->assertEquals( 'foo', $this->replaceVars( 'foo' ), "Don't break anything accidentally" );
130 "CREATE TABLE /**/foo (foo_key INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
131 . "foo_bar TEXT, foo_name TEXT NOT NULL DEFAULT '', foo_int INTEGER, foo_int2 INTEGER );",
133 "CREATE TABLE /**/foo (foo_key int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, "
134 . "foo_bar char(13), foo_name varchar(255) binary NOT NULL DEFAULT '', "
135 . "foo_int tinyint ( 8 ), foo_int2 int(16) ) ENGINE=MyISAM;"
140 "CREATE TABLE foo ( foo1 REAL, foo2 REAL, foo3 REAL );",
142 "CREATE TABLE foo ( foo1 FLOAT, foo2 DOUBLE( 1,10), foo3 DOUBLE PRECISION );"
146 $this->assertEquals( "CREATE TABLE foo ( foo_binary1 BLOB, foo_binary2 BLOB );",
147 $this->replaceVars( "CREATE TABLE foo ( foo_binary1 binary(16), foo_binary2 varbinary(32) );" )
150 $this->assertEquals( "CREATE TABLE text ( text_foo TEXT );",
151 $this->replaceVars( "CREATE TABLE text ( text_foo tinytext );" ),
155 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
156 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY NOT NULL AUTO_INCREMENT );" )
158 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
159 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY AUTO_INCREMENT NOT NULL );" )
162 $this->assertEquals( "CREATE TABLE enums( enum1 TEXT, myenum TEXT)",
163 $this->replaceVars( "CREATE TABLE enums( enum1 ENUM('A', 'B'), myenum ENUM ('X', 'Y'))" )
166 $this->assertEquals( "ALTER TABLE foo ADD COLUMN foo_bar INTEGER DEFAULT 42",
167 $this->replaceVars( "ALTER TABLE foo\nADD COLUMN foo_bar int(10) unsigned DEFAULT 42" )
170 $this->assertEquals( "DROP INDEX foo",
171 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar" )
174 $this->assertEquals( "DROP INDEX foo -- dropping index",
175 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar -- dropping index" )
177 $this->assertEquals( "INSERT OR IGNORE INTO foo VALUES ('bar')",
178 $this->replaceVars( "INSERT OR IGNORE INTO foo VALUES ('bar')" )
183 * @covers DatabaseSqlite::tableName
185 public function testTableName() {
187 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
188 $this->assertEquals( 'foo', $db->tableName( 'foo' ) );
189 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
190 $db->tablePrefix( 'foo' );
191 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
192 $this->assertEquals( 'foobar', $db->tableName( 'bar' ) );
196 * @covers DatabaseSqlite::duplicateTableStructure
198 public function testDuplicateTableStructure() {
199 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
200 $db->query( 'CREATE TABLE foo(foo, barfoo)' );
201 $db->query( 'CREATE INDEX index1 ON foo(foo)' );
202 $db->query( 'CREATE UNIQUE INDEX index2 ON foo(barfoo)' );
204 $db->duplicateTableStructure( 'foo', 'bar' );
205 $this->assertEquals( 'CREATE TABLE "bar"(foo, barfoo)',
206 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'bar' ] ),
207 'Normal table duplication'
209 $indexList = $db->query( 'PRAGMA INDEX_LIST("bar")' );
210 $index = $indexList->next();
211 $this->assertEquals( 'bar_index1', $index->name
);
212 $this->assertEquals( '0', $index->unique
);
213 $index = $indexList->next();
214 $this->assertEquals( 'bar_index2', $index->name
);
215 $this->assertEquals( '1', $index->unique
);
217 $db->duplicateTableStructure( 'foo', 'baz', true );
218 $this->assertEquals( 'CREATE TABLE "baz"(foo, barfoo)',
219 $db->selectField( 'sqlite_temp_master', 'sql', [ 'name' => 'baz' ] ),
220 'Creation of temporary duplicate'
222 $indexList = $db->query( 'PRAGMA INDEX_LIST("baz")' );
223 $index = $indexList->next();
224 $this->assertEquals( 'baz_index1', $index->name
);
225 $this->assertEquals( '0', $index->unique
);
226 $index = $indexList->next();
227 $this->assertEquals( 'baz_index2', $index->name
);
228 $this->assertEquals( '1', $index->unique
);
229 $this->assertEquals( 0,
230 $db->selectField( 'sqlite_master', 'COUNT(*)', [ 'name' => 'baz' ] ),
231 'Create a temporary duplicate only'
236 * @covers DatabaseSqlite::duplicateTableStructure
238 public function testDuplicateTableStructureVirtual() {
239 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
240 if ( $db->getFulltextSearchModule() != 'FTS3' ) {
241 $this->markTestSkipped( 'FTS3 not supported, cannot create virtual tables' );
243 $db->query( 'CREATE VIRTUAL TABLE "foo" USING FTS3(foobar)' );
245 $db->duplicateTableStructure( 'foo', 'bar' );
246 $this->assertEquals( 'CREATE VIRTUAL TABLE "bar" USING FTS3(foobar)',
247 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'bar' ] ),
248 'Duplication of virtual tables'
251 $db->duplicateTableStructure( 'foo', 'baz', true );
252 $this->assertEquals( 'CREATE VIRTUAL TABLE "baz" USING FTS3(foobar)',
253 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'baz' ] ),
254 "Can't create temporary virtual tables, should fall back to non-temporary duplication"
259 * @covers DatabaseSqlite::deleteJoin
261 public function testDeleteJoin() {
262 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
263 $db->query( 'CREATE TABLE a (a_1)', __METHOD__
);
264 $db->query( 'CREATE TABLE b (b_1, b_2)', __METHOD__
);
273 [ 'b_1' => 2, 'b_2' => 'a' ],
274 [ 'b_1' => 3, 'b_2' => 'b' ],
278 $db->deleteJoin( 'a', 'b', 'a_1', 'b_1', [ 'b_2' => 'a' ], __METHOD__
);
279 $res = $db->query( "SELECT * FROM a", __METHOD__
);
280 $this->assertResultIs( [
288 public function testEntireSchema() {
291 $result = Sqlite
::checkSqlSyntax( "$IP/maintenance/tables.sql" );
292 if ( $result !== true ) {
293 $this->fail( $result );
295 $this->assertTrue( true ); // avoid test being marked as incomplete due to lack of assertions
299 * Runs upgrades of older databases and compares results with current schema
300 * @todo Currently only checks list of tables
302 public function testUpgrades() {
303 global $IP, $wgVersion, $wgProfiler;
307 // '1.13', disabled for now, was totally screwed up
308 // SQLite wasn't included in 1.14
320 // Mismatches for these columns we can safely ignore
322 'user_newtalk.user_last_timestamp', // r84185
325 $currentDB = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
326 $currentDB->sourceFile( "$IP/maintenance/tables.sql" );
328 $profileToDb = false;
329 if ( isset( $wgProfiler['output'] ) ) {
330 $out = $wgProfiler['output'];
331 if ( $out === 'db' ) {
333 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
338 if ( $profileToDb ) {
339 $currentDB->sourceFile( "$IP/maintenance/sqlite/archives/patch-profiling.sql" );
341 $currentTables = $this->getTables( $currentDB );
342 sort( $currentTables );
344 foreach ( $versions as $version ) {
345 $versions = "upgrading from $version to $wgVersion";
346 $db = $this->prepareTestDB( $version );
347 $tables = $this->getTables( $db );
348 $this->assertEquals( $currentTables, $tables, "Different tables $versions" );
349 foreach ( $tables as $table ) {
350 $currentCols = $this->getColumns( $currentDB, $table );
351 $cols = $this->getColumns( $db, $table );
353 array_keys( $currentCols ),
355 "Mismatching columns for table \"$table\" $versions"
357 foreach ( $currentCols as $name => $column ) {
358 $fullName = "$table.$name";
361 (bool)$cols[$name]->pk
,
362 "PRIMARY KEY status does not match for column $fullName $versions"
364 if ( !in_array( $fullName, $ignoredColumns ) ) {
366 (bool)$column->notnull
,
367 (bool)$cols[$name]->notnull
,
368 "NOT NULL status does not match for column $fullName $versions"
372 $cols[$name]->dflt_value
,
373 "Default values does not match for column $fullName $versions"
377 $currentIndexes = $this->getIndexes( $currentDB, $table );
378 $indexes = $this->getIndexes( $db, $table );
380 array_keys( $currentIndexes ),
381 array_keys( $indexes ),
382 "mismatching indexes for table \"$table\" $versions"
390 * @covers DatabaseSqlite::insertId
392 public function testInsertIdType() {
393 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
395 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__
);
396 $this->assertInstanceOf( 'ResultWrapper', $databaseCreation, "Database creation" );
398 $insertion = $db->insert( 'a', [ 'a_1' => 10 ], __METHOD__
);
399 $this->assertTrue( $insertion, "Insertion worked" );
401 $this->assertInternalType( 'integer', $db->insertId(), "Actual typecheck" );
402 $this->assertTrue( $db->close(), "closing database" );
405 private function prepareTestDB( $version ) {
406 static $maint = null;
407 if ( $maint === null ) {
408 $maint = new FakeMaintenance();
409 $maint->loadParamsAndArgs( null, [ 'quiet' => 1 ] );
413 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
414 $db->sourceFile( "$IP/tests/phpunit/data/db/sqlite/tables-$version.sql" );
415 $updater = DatabaseUpdater
::newForDB( $db, false, $maint );
416 $updater->doUpdates( [ 'core' ] );
421 private function getTables( $db ) {
422 $list = array_flip( $db->listTables() );
424 'external_user', // removed from core in 1.22
425 'math', // moved out of core in 1.18
426 'trackbacks', // removed from core in 1.19
428 'searchindex_content',
429 'searchindex_segments',
430 'searchindex_segdir',
432 'searchindex_docsize',
435 foreach ( $excluded as $t ) {
438 $list = array_flip( $list );
444 private function getColumns( $db, $table ) {
446 $res = $db->query( "PRAGMA table_info($table)" );
447 $this->assertNotNull( $res );
448 foreach ( $res as $col ) {
449 $cols[$col->name
] = $col;
456 private function getIndexes( $db, $table ) {
458 $res = $db->query( "PRAGMA index_list($table)" );
459 $this->assertNotNull( $res );
460 foreach ( $res as $index ) {
461 $res2 = $db->query( "PRAGMA index_info({$index->name})" );
462 $this->assertNotNull( $res2 );
463 $index->columns
= [];
464 foreach ( $res2 as $col ) {
465 $index->columns
[] = $col;
467 $indexes[$index->name
] = $index;
474 public function testCaseInsensitiveLike() {
475 // TODO: Test this for all databases
476 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
477 $res = $db->query( 'SELECT "a" LIKE "A" AS a' );
478 $row = $res->fetchRow();
479 $this->assertFalse( (bool)$row['a'] );
483 * @covers DatabaseSqlite::numFields
485 public function testNumFields() {
486 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
488 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__
);
489 $this->assertInstanceOf( 'ResultWrapper', $databaseCreation, "Failed to create table a" );
490 $res = $db->select( 'a', '*' );
491 $this->assertEquals( 0, $db->numFields( $res ), "expects to get 0 fields for an empty table" );
492 $insertion = $db->insert( 'a', [ 'a_1' => 10 ], __METHOD__
);
493 $this->assertTrue( $insertion, "Insertion failed" );
494 $res = $db->select( 'a', '*' );
495 $this->assertEquals( 1, $db->numFields( $res ), "wrong number of fields" );
497 $this->assertTrue( $db->close(), "closing database" );
500 public function testToString() {
501 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
503 $toString = (string)$db;
505 $this->assertContains( 'SQLite ', $toString );